package cn.me.syn;

/**
 * @author jia
 * @date 2021/2/21
 */
/*
线程不安全有负数
 */

public class UnsafeByTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station, "小明").start();
        new Thread(station, "厉害").start();
        new Thread(station, "黄牛").start();
    }

}

class BuyTicket implements Runnable {

    private int ticketnumber = 10;
    boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
//synchronized同步方法
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketnumber <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketnumber--);
    }
}
